<template>
  <div class="AddOrUpdate_main add_container column_two">
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="合同评审单" prop="code">
          <CodeRuleInput
            :band-value.sync="formData.code"
            table-name="sale_review"
            column-name="code"
            :is-edit="id"
          />
        </el-form-item>
        <el-form-item label="制单人员">
          <el-input v-model="formData.reviewName" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="制单日期">
          <el-date-picker
            v-model="formData.reviewTime"
            type="date"
            placeholder="选择日期"
            :editable="false"
          />
        </el-form-item>
        <el-form-item label="客户特殊要求" class="double">
          <el-input
            v-model="formData.specialRequire"
            type="textarea"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item label="备注" class="double">
          <el-input
            v-model="formData.remark"
            type="textarea"
            placeholder="请输入"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div class="formItem_header">
        <!-- 订单明细 -->
        <div />
        <div class="formItem_header_operate">
          <a class="formItem_header_operate_item" @click="addRow">
            <svg-icon icon-class="新增" />
            <div class="item_name">添加</div>
          </a>
          <!-- <el-button
              class="esc"
              @click.stop="importData"
            >导入</el-button> -->
          <a class="formItem_header_operate_item delete" @click="deleteRow">
            <svg-icon icon-class="删除" />
            <div class="item_name">删除</div>
          </a>
        </div>
      </div>
      <div
        ref="table_container"
        class="table_container draggableTable"
      >
        <el-table
          ref="table"
          :key="tableKey"
          :data="listData"
          :height="tableHeight"
          stripe
          border
          row-key="id"
          style="width: 99.9%;"
          :cell-class-name="cellClassName"
          :row-class-name="rowClassName"
          @selection-change="selectionChange"
        >
          <el-table-column type="selection" align="center" />
          <el-table-column label="客户订单号" min-width="120" prop="saleCustomerOrderCode" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.saleCustomerOrderCode }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料编码" min-width="120" prop="materialCode" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialCode }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料名称" min-width="100" prop="materialName" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="规格型号" min-width="100" prop="materialModel" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialModel }}</span>
            </template>
          </el-table-column>
          <el-table-column label="客户料号" min-width="100" prop="saleCustomerMaterialCode" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.saleCustomerMaterialCode }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料单位" min-width="100" prop="materialUnitName" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialUnitName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="订单数量" :min-width="SETTINGS.settings_decimalDigits_length" prop="orderNumber" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.orderNumber }}</span>
            </template>
          </el-table-column>
          <el-table-column label="客户交期" min-width="140" prop="saleCustomerDeliveryTime" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.saleCustomerDeliveryTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="评审交期" min-width="140" prop="saleCustomerDeliveryTime">
            <template slot-scope="scope">
              <el-date-picker
                v-model="scope.row.approvalDeliveryTime"

                type="date"
                placeholder="选择日期"
                :editable="false"
              />
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="200" prop="remark">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入" clearable />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="onSubmit">提交</el-button>
    </div>
  </div>
</template>

<script>
import {
  addOrUpdate,
  getInfo
} from '@/api/saleManage/saleReview'
import moment from 'moment'
import chooseOrder from './chooseOrder.vue'
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    defaultValue: {},
    isAdd: {}
  },
  data() {
    const validateOrderTime = (rule, value, callback) => {
      console.log(value)
      if (value.getTime() > Date.now()) {
        callback(new Error('制单日期不可超过当前日期'))
      } else {
        callback()
      }
    }
    return {
      pageData: {
        pageNum: 1,
        pageSize: 9999,
        orderByColumn: 'updateTime',
        isAsc: 'desc'
      },
      tableKey: '',
      formData: {
        code: '',
        reviewName: '',
        reviewBy: '',
        specialRequire: '',
        reviewTime: '',
        remark: '',
        details: [],
        id: ''
      },
      saveData: [],
      mainId: 'orderDetailId',
      selections: [], // 表格当前页所选中的行
      selectionsAll: [], // 表格所有页选中的行
      listData: [],
      taxRateCodeList: [],
      tableHeight: '260',
      showSummary: true,
      templateSelection: '',
      tableData: [],
      peopleData: {},
      rules: {
        code: [
          { required: true, message: '销售订单号不能为空', trigger: 'blur' }
        ],
        orderTime: [
          { validator: validateOrderTime, trigger: 'change' }
        ],
        customerName: [
          { required: true, message: '客户名称不能为空', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    if (!this.id) {
      // 没有id就是新增
      Object.keys(this.defaultValue).forEach((key) => {
        // 给右边数据赋值
        this.formData[key] = this.defaultValue[key]
      })
    } else {
      // 有id就是编辑
      this.getInfo()
      this.formData.id = this.id
    }
  },
  mounted() {
    this.formData.reviewName = this.$store.state.user.name
    this.formData.reviewBy = this.$store.state.user.userId
    this.formData.reviewTime = moment(new Date()).format('YYYY-MM-DD')
  },
  methods: {
    headStyle() {
      return 'text-align:center'
    },
    importData() {

    },
    selectionChange(e) {
      this.selectionsAll = e
    },
    showOrder(data) {
      const cacheData = []
      data.forEach((item, index) => {
        if (this.listData.some(item2 => item2.orderDetailId == item.orderDetailId)) {
          cacheData.push(this.listData.filter(item2 => item2.orderDetailId == item.orderDetailId)[0])
        } else {
          item.remark = ''
          cacheData.push(item)
        }
        if (index == data.length - 1) {
          this.listData = this.$deepClone(cacheData)
        }
      })
    },
    cellClassName(data) {
      if (data.column.property == 'operate') {
        if (data.rowIndex % 2 == 0) {
          // 单数行
          return 'fixed one'
        } else {
          // 双数行
          return 'fixed two'
        }
      }
    },
    rowClassName({ row, rowIndex }) {
      if (rowIndex == this.tableData.length - 1) {
        return 'addRow'
      }
    },
    addRow() {
      this.$layer.iframe({
        // 弹框
        content: {
          content: chooseOrder, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            selectedRow: this.listData
          } // props
        },
        area: ['1000px', '700px'],
        title: '选择订单明细', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    deleteRow() {
      this.selectionsAll.forEach(item => {
        this.listData.splice(this.listData.indexOf(item), 1)
      })
      if (this.formData.id) {
        if (this.listData.length > 0) {
          this.listData.forEach(ele => {
            this.listData.some(ele => {
              const data = this.saveData.find(item => item.orderDetailId == ele.orderDetailId)
              if (!data) {
                delete ele.id
              }
            })
          })
        }
        this.formData.details = JSON.parse(JSON.stringify(this.listData))
        addOrUpdate(this.formData).then((res) => {
          this.$message({
            message: res.msg,
            type: 'success'
          })
        })
      }
    },
    getInfo() {
      getInfo(this.id).then((res) => {
        Object.keys(this.formData).forEach((key) => {
          // 给右边数据赋值
          this.formData[key] = res.data[key]
        })

        this.listData = this.formData.details
        this.saveData = this.$deepClone(this.listData)
      })
    },
    // 提交
    onSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.listData.length > 0) {
            this.listData.forEach(ele => {
              if (!this.formData.id) {
                delete ele.id
              } else {
                this.listData.some(ele => {
                  const data = this.saveData.find(item => item.orderDetailId == ele.orderDetailId)
                  if (!data) {
                    delete ele.id
                  }
                })
              }
            })
            this.listData.forEach(ele => {
              if (ele.approvalDeliveryTime) {
                ele.approvalDeliveryTime = moment(ele.approvalDeliveryTime).format('YYYY-MM-DD')
              }
            })
            this.formData.reviewTime = this.formData.reviewTime ? moment(this.formData.reviewTime).format('YYYY-MM-DD') : ''
            this.formData.details = JSON.parse(JSON.stringify(this.listData))
            addOrUpdate(this.formData).then((res) => {
              this.$message({
                message: res.msg,
                type: 'success'
              })
              this.$layer.close(this.layerid) // 关闭弹框
              this.$parent.getList() // 调用父组件的刷新方法
            })
          } else {
            this.$message.warning('请添加订单明细')
            return
          }
        }
      })
    },
    cancel() {
      this.$layer.close(this.layerid) // 关闭弹框
    }
    //
  }
}
</script>

<style lang="less" scoped>
.title {
  padding-left: 20px;
  padding-bottom: 20px;
  font-size: 24px;
  width: 100%;
}
.numberComponents {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
}
/deep/ .el-input-number.is-controls-right .el-input-number__increase {
  height: 15px;
}
.el-icon-remove {
  font-size: 25px;
  color: red;
  height: 100%;
  width: 100%;
  border: 0px;
  background-color: transparent;
}
/deep/ .el-form-item__content {
  margin-left: 0 !important;
}
/deep/ .el-form-item__label {
  text-align: right;
}
.expand_radio {
  /deep/ .el-form-item__content {
    text-align: left;
  }
}
.expand_container {
  .el-form-item {
    margin-bottom: 10px;
  }
  .expand_file {
    margin-bottom: 0px;
  }

  /deep/ .el-form-item__label {
    width: 130px !important;
  }
  /deep/ .el-form-item__content {
    width: 710px !important;
  }
}
.main_main {
  .form_padding {
    padding: 0 !important;
    /deep/ .el-form-item {
      margin-right: 0px;
    }
    /deep/ .el-form-item__label {
      width: 120px !important;
    }
    /deep/ .el-form-item__content {
      width: 270px;
    }
    .remark {
      /deep/ .el-form-item__content {
        width: 690px !important;
        height: 60px;
        overflow-y: auto;
      }
    }
  }
}
/deep/ .el-table th.el-table__cell > .cell {
  position: unset;
}
.order_header{
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  .info_button{
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-end;
  }
}
</style>
